package com.yx.cloud.view;

import android.content.Context;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.viewpager.widget.ViewPager;

public class CarouselViewPager extends ViewPager {
    private float xDistance, yDistance;
    /** 触摸时按下的点 **/
    PointF downP = new PointF();
    /** 触摸时当前的点 **/
    PointF curP = new PointF();

    public CarouselViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public CarouselViewPager(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        // TODO Auto-generated method stub
        if(arg0.getAction() == MotionEvent.ACTION_DOWN) {
            //记录按下时候的坐标
            //切记不可用 downP = curP ，这样在改变curP的时候，downP也会改变
            xDistance = yDistance = 0f;
            downP.x = arg0.getX();
            downP.y = arg0.getY();
            //此句代码是为了通知他的父ViewPager现在进行的是本控件的操作，不要对我的操作进行干扰
            getParent().requestDisallowInterceptTouchEvent(true);
        }

        if(arg0.getAction() == MotionEvent.ACTION_MOVE){
            curP.x = arg0.getX();
            curP.y = arg0.getY();
            //此句代码是为了通知他的父ViewPager现在进行的是本控件的操作，不要对我的操作进行干扰
            xDistance += Math.abs(curP.x - downP.x);
            yDistance += Math.abs(curP.y - downP.y);
            downP.x = curP.x;
            downP.y = curP.y;

            if (xDistance > yDistance) {
                getParent().requestDisallowInterceptTouchEvent(true);
                super.onTouchEvent(arg0); //注意这句不能 return super.onTouchEvent(arg0); 否则触发parent滑动
                return true;
            }else if(yDistance > 10){
                getParent().requestDisallowInterceptTouchEvent(false);
                super.onTouchEvent(arg0);
                return false;
            }
        }
        return super.onTouchEvent(arg0);
    }
}
